<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="./bootstrap.min.css" />
    <style>
      .container1 {
        /* margin-top: 10px;-1 */
        display: flex;
        background-color: pink;
        padding: 0 5px 10px 10px;
      }
      .mb-3 {
        flex: 2;
        margin-right: 5px;
      }
      .img-cell img {
        max-width: 150px;
        max-height: 150px;
        cursor: pointer;
      }
      #data-input {
        height: 80vh;
      }
      .status-bar {
        flex: 5;
        font-weight: bold;
      }
      .abc {
        height: 200px;
        overflow: hidden;
      }
      .selected-row {
        background-color: #0d6efd !important; /* Bootstrap 主色高亮 */
        color: white;
      }
      /* 图片预览样式 */
      .preview-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        justify-content: center;
        align-items: center;
        z-index: 9999;
      }
      .preview-modal img {
        max-width: 80%;
        max-height: 80%;
      }
      .preview-nav {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(255, 255, 255, 0.3);
        padding: 10px;
        border-radius: 5px;
      }
      .preview-nav.left {
        left: 20px;
      }
      .preview-nav.right {
        right: 20px;
      }
      .preview-nav button {
        background: transparent;
        border: none;
        font-size: 24px;
        cursor: pointer;
      }
      .table-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .paginationBox {
        position: fixed;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
      }
      .justify-content-end {
        display: flex;
        flex-wrap: wrap;
        /* flex-direction: column; */
      }
      ul {
        display: flex;
        flex-wrap: wrap;
        justify-content: start;
        user-select: none;
      }
      ul li {
        text-align: center;
        user-select: none;
      }
      #total-count {
        font-size: 20px;
      }
      #selected-count {
        font-size: 20px;
        color: red;
      }
      .table-bordered {
        height: 300px;
        margin-top: 10px;
      }
      .page-link {
        cursor: pointer;
      }
      .abc {
        height: 200px;
        overflow: auto; /* 改为 auto 而不是 hidden，以便滚动 */
      }

      /* 表格行 效果 */
      .table-bordered tbody tr:hover {
        background-color: pink !important;
      }

      /* 选中行样式 */
      .selected-row {
        background-color: #0d6efd !important;
        color: white;
      }

      /* 选中行在 hover 时保持样式 */
      .table-bordered tbody tr.selected-row:hover {
        background-color: pink !important;
        color: white !important;
      }
    </style>
  </head>
  <body>
    <!-- 分页控件 -->
    <nav aria-label="Page navigation" class="paginationBox1">
      <ul class="pagination justify-content-end" id="pagination"></ul>
    </nav>
    <div class="container1">
      <div class="mb-3">
        <div class="table-title">
          数据总数: <span id="total-count">0</span> | 选中数量:<span
            id="selected-count"
            >0</span
          >
          <!-- <button class="btn btn-success mt-2" onclick="fileImportData()">上传 JSON 文件</button> -->
          <button class="btn btn-primary mt-2" onclick="exportSelectedData()">
            导出选中数据
          </button>
        </div>
        <textarea
          id="data-input"
          class="form-control"
          placeholder="在此粘贴 JSON 数据（或上传文件）"
          oninput="autoImportData()"
        ></textarea>
      </div>

      <!-- 状态栏 -->
      <div class="status-bar" id="status-bar">
        <div class="table-container">
          <table class="table table-bordered table-hover">
            <thead>
              <tr>
                <th scope="col">#</th>
                <th scope="col">SPM ID</th>
                <th scope="col">图片</th>
                <th scope="col">标题</th>
              </tr>
            </thead>
            <tbody id="table-body" class="abc"></tbody>
          </table>
        </div>
      </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

    <script>
      let data = [];
      let currentPage = 1;
      const itemsPerPage = 10;
      let selectedIndices = new Set(); // 存储选中行的原始索引
      let previewImages = []; // 存储选中图片的数组
      let currentPreviewIndex = 0; // 当前预览图片的索引

      // 自动解析粘贴的 JSON
      function autoImportData() {
        const input = document.getElementById("data-input").value.trim();
        try {
          if (input) {
            data = JSON.parse(input);
            currentPage = 1;
            selectedIndices.clear(); // 清空旧的选中状态
            renderTable();
            renderPagination();
            updateStatusBar(); // 更新状态栏
          }
        } catch (error) {
          alert("粘贴的 JSON 格式错误，请检查数据格式");
        }
      }

      // 文件上传解析
      function fileImportData() {
        const fileInput = document.createElement("input");
        fileInput.type = "file";
        fileInput.accept = ".json";
        fileInput.onchange = (e) => {
          const file = e.target.files[0];
          if (file) {
            const reader = new FileReader();
            reader.onload = () => {
              try {
                data = JSON.parse(reader.result);
                currentPage = 1;
                selectedIndices.clear(); // 清空旧的选中状态
                renderTable();
                renderPagination();
                updateStatusBar(); // 更新状态栏
              } catch (error) {
                alert("文件格式错误，请上传有效的 JSON 文件");
              }
            };
            reader.readAsText(file);
          }
        };
        fileInput.click();
      }

      // 渲染表格
      function renderTable() {
        const tbody = document.getElementById("table-body");
        const start = (currentPage - 1) * itemsPerPage;
        const end = start + itemsPerPage;
        const pageData = data.slice(start, end);

        // 清空表格
        tbody.innerHTML = "";

        // 渲染当前页数据
        pageData.forEach((item, index) => {
          const row = tbody.insertRow();
          const rowIndex = start + index;

          // 行点击事件
          row.addEventListener("click", (e) => {
            const checkbox = e.target.closest("input[type='checkbox']");
            if (!checkbox) {
              toggleSelection(rowIndex);
            }
          });

          // 行号列
          const serialCell = row.insertCell();
          serialCell.textContent = rowIndex + 1;
          serialCell.style.cursor = "pointer";

          // 多选复选框
          const checkboxCell = row.insertCell();
          const checkbox = document.createElement("input");
          checkbox.type = "checkbox";
          checkbox.dataset.index = rowIndex;
          checkbox.checked = selectedIndices.has(rowIndex); // 从全局变量恢复状态
          checkboxCell.appendChild(checkbox);
          checkboxCell.style.cursor = "pointer";

          // 图片
          const imgCell = row.insertCell();
          const img = document.createElement("img");
          img.src = item.imgSrc;
          img.alt = "商品图片";
          img.className = "img-fluid rounded";
          imgCell.className = "img-cell";
          imgCell.appendChild(img);

          // 标题
          const titleCell = row.insertCell();
          titleCell.textContent = item.title;
          titleCell.style.cursor = "pointer";
        });
      }

      // 切换选中状态
      function toggleSelection(index) {
        if (selectedIndices.has(index)) {
          selectedIndices.delete(index);
        } else {
          selectedIndices.add(index);
        }
        renderTable(); // 重新渲染表格以同步状态
        updateStatusBar(); // 更新状态栏
      }

      // 更新状态栏
      function updateStatusBar() {
        document.getElementById("total-count").textContent = data.length;
        document.getElementById("selected-count").textContent =
          selectedIndices.size;
      }

      // 渲染分页
      function renderPagination() {
        const totalPages = Math.ceil(data.length / itemsPerPage);
        const pagination = document.getElementById("pagination");
        pagination.innerHTML = "";

        // 上一页按钮
        const prevLi = document.createElement("li");
        prevLi.className = `page-item ${currentPage === 1 ? "disabled" : ""}`;
        const prevA = document.createElement("a");
        prevA.className = "page-link";
        prevA.textContent = "上一页";
        prevA.addEventListener("click", () => {
          if (currentPage > 1) {
            currentPage--;
            renderTable();
            renderPagination();
          }
        });
        prevLi.appendChild(prevA);
        pagination.appendChild(prevLi);

        // 数字分页
        for (let i = 1; i <= totalPages; i++) {
          const li = document.createElement("li");
          li.className = `page-item ${i === currentPage ? "active" : ""}`;
          const a = document.createElement("a");
          a.className = "page-link";
          a.textContent = i;
          a.addEventListener("click", () => {
            currentPage = i;
            renderTable();
            renderPagination();
          });
          li.appendChild(a);
          pagination.appendChild(li);
        }

        // 下一页按钮
        const nextLi = document.createElement("li");
        nextLi.className = `page-item ${
          currentPage === totalPages ? "disabled" : ""
        }`;
        const nextA = document.createElement("a");
        nextA.className = "page-link";
        nextA.textContent = "下一页";
        nextA.addEventListener("click", () => {
          if (currentPage < totalPages) {
            currentPage++;
            renderTable();
            renderPagination();
          }
        });
        nextLi.appendChild(nextA);
        pagination.appendChild(nextLi);
      }

      // 导出选中数据
      function exportSelectedData() {
        if (selectedIndices.size === 0) {
          alert("欢姐,请勾选数据!!!");
          return;
        }

        const selectedData = Array.from(selectedIndices).map(
          (index) => data[index]
        );
        const csvContent = convertToCSV(selectedData);
        downloadCSV(csvContent, "选中商品数据.csv");
      }

      // 转换为 CSV 格式
      function convertToCSV(data) {
        const header = ["SPM 活动 ID"];
        const rows = data.map((item) => [item.spmActId]);

        const csv =
          "\uFEFF" +
          [header, ...rows]
            .map((row) => row.map((cell) => `"${cell}"`).join(","))
            .join("\n");

        return csv;
      }

      // 触发下载
      function downloadCSV(content, filename) {
        const blob = new Blob([content], { type: "text/csv;charset=utf-8;" });
        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        link.click();
      }

      // 图片预览功能
      function initImagePreview() {
        const images = document.querySelectorAll(".img-cell img");
        images.forEach((img, index) => {
          const dataIndex = parseInt(
            img.closest("tr").querySelector("input[type='checkbox']").dataset
              .index
          );
          img.addEventListener("click", () => {
            if (selectedIndices.has(dataIndex)) {
              previewImages = Array.from(selectedIndices).map(
                (i) => data[i].imgSrc
              );
              currentPreviewIndex = previewImages.indexOf(
                data[dataIndex].imgSrc
              );
              showPreview(currentPreviewIndex);
            } else {
              alert("请先选中该图片对应的行");
            }
          });
        });
      }

      // 显示预览
      function showPreview(index) {
        const modal = document.getElementById("previewModal");
        const img = document.getElementById("previewImage");
        img.src = previewImages[index];
        modal.style.display = "flex";
        currentPreviewIndex = index;
      }

      // 上一张/下一张切换
      function navigatePreview(direction) {
        currentPreviewIndex += direction;
        if (currentPreviewIndex < 0)
          currentPreviewIndex = previewImages.length - 1;
        if (currentPreviewIndex >= previewImages.length)
          currentPreviewIndex = 0;
        showPreview(currentPreviewIndex);
      }

      // 自动绑定图片预览事件
      renderTable(); // 初始渲染
      initImagePreview();
    </script>
  </body>
</html>
